package com.samuel.blog.tag;

import com.samuel.blog.constant.CommonConstant;
import com.samuel.blog.entity.AuthorEntity;
import com.samuel.blog.entity.JurisdictionEntity;
import com.samuel.blog.entity.RoleEntity;
import com.samuel.blog.service.AuthorService;
import freemarker.core.Environment;
import freemarker.template.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author kaiji
 */
public class PrivUrlTag implements TemplateDirectiveModel {

	@Resource(name = "authorService")
	private AuthorService authorService;
	
	@Override
    @SuppressWarnings("rawtypes")
	public void execute(Environment env, Map map, TemplateModel[] tm, TemplateDirectiveBody td)
			throws TemplateException, IOException {
        try {
        		HttpServletRequest request = getRequest(); 
            // 获取session里面的用户
        		AuthorEntity author = (AuthorEntity)request.getSession().getAttribute(CommonConstant.USER_LOGIN_SESSION_KEY);

        		RoleEntity roleEntity = authorService.selectRoleByRedis(author.getAuthorId());
        		List<JurisdictionEntity> list = authorService.selectJurByRedis(author.getAuthorId());
        		
        		if (null == roleEntity) {
        			env.getOut().write("");
        			return;
        		}
        		/**  测试
        		String str = map.get("code").toString();
        		if ("A00103".equals(str)) {
        			System.out.println("code is A00103");
        		}
        		**/
        		if (CommonConstant.ADMIN_ROLE_ID.equals(roleEntity.getRoleId())) {
        			td.render(env.getOut());
        		} else {
        			if (null == list || list.size() <= 0 || list.get(0) == null) {
        				env.getOut().write("");
        				return;
        			} else {
        				if (map.isEmpty()) {
        					throw new TemplateModelException("最起码要一个参数！");
        				}
        				String object = map.get("code").toString();
        				if (null == object) {
        					throw new TemplateModelException("必须是code！");
        				}
        				
        				if (checkPrivUrl(object, list)) {
        					td.render(env.getOut());
        				} else {
        					env.getOut().write("");
        					return;
        				}
        			}     
        		}
        		
        		
        	} catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }   
	}

	/**
	 * 检测权限
	 * @param privUrl 请求的URL
	 * @param list    自己的权限URL
	 * @return
	 */
	private boolean checkPrivUrl(String privUrl, List<JurisdictionEntity> list) {
		for (JurisdictionEntity jur : list) {
			if (privUrl.equals(jur.getCode())) {
				return true;
			}
		}
		return false;
	}
	
	private HttpServletRequest getRequest() {
		ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        return attr.getRequest();
	}

}
